package com.ushio.authservice.department.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ushio.authservice.department.entity.vo.DepartmentVo;
import com.ushio.authservice.department.mapper.DepartmentMapper;
import com.ushio.authservice.department.service.DepartmentService;
import com.ushio.commonmodule.pojo.department.Department;
import com.ushio.commonmodule.pojo.result.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Autowired
    DepartmentMapper departmentMapper;
    @Override
    public List<DepartmentVo> getDepartmentAll() {

        List<Department> departments = departmentMapper.selectList(new LambdaQueryWrapper<>());


        List<DepartmentVo> departmentVoList = buildDepartmentTree(departments);

        return departmentVoList;
    }

    public  List<DepartmentVo> buildDepartmentTree(List<Department> departmentList) {
        // 先转成 VO 列表
        Map<Integer, DepartmentVo> idToVoMap = new HashMap<>();
        for (Department dept : departmentList) {
            DepartmentVo vo = convertToVo(dept);
            idToVoMap.put(vo.getDepartmentId(), vo);
        }

        List<DepartmentVo> rootList = new ArrayList<>();

        for (Department dept : departmentList) {
            DepartmentVo vo = idToVoMap.get(dept.getDepartmentId());
            Integer parentId = dept.getDepartmentSuperiorId();
            if (parentId == null) {
                // 顶层部门
                rootList.add(vo);
            } else {
                DepartmentVo parentVo = idToVoMap.get(parentId);
                if (parentVo != null) {
                    parentVo.getChildren().add(vo);
                }
            }
        }

        return rootList;
    }

    public  DepartmentVo convertToVo(Department dept) {
        return DepartmentVo.builder()
                .departmentId(dept.getDepartmentId())
                .departmentName(dept.getDepartmentName())
                .departmentSuperiorId(dept.getDepartmentSuperiorId())
                .createTime(dept.getCreateTime())
                .updateTime(dept.getUpdateTime())
                .createUser(dept.getCreateUser())
                .updateUser(dept.getUpdateUser())
                .remove(dept.getRemove())
                .children(new ArrayList<>()) // 初始化避免空指针
                .build();
    }


}
